package cn.cubix.flow.controller.workflow;

import cn.cubix.flow.controller.dto.workflow.TodoTaskDto;
import cn.cubix.flow.util.Result;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.*;
import org.flowable.engine.impl.RuntimeServiceImpl;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/workflow/todotask")
@RequiredArgsConstructor(onConstructor=@__({@Autowired,@Lazy}))
public class TodoTaskApi {

    private final RuntimeServiceImpl runtimeService;
    private final TaskService taskService;
    private final ProcessEngine processEngine;

    @Setter(onMethod=@__(@Autowired),onParam = @__(@Lazy))
    private RepositoryService repositoryService;
    @Setter(onMethod=@__(@Autowired),onParam = @__(@Lazy))
    private HistoryService historyService;

    /** 分页查询流程待办任务 */
    @PostMapping(value = "/page",consumes = {MediaType.APPLICATION_JSON_VALUE})
    @PreAuthorize("hasAnyAuthority('ADMIN','API_WORKFLOW_TODOTASK_PAGE')")
    public Object todo(@RequestBody JSONObject body){
        long current = 1L, size = 10L, total = 0L, start = 0L;
        if(body.containsKey("page")){
            JSONObject page = body.getJSONObject("page");
            current = page.getInt("current");
            size = page.getInt("size");
            start = (current-1)*size;
        }

        String assignee = "";
        if(body.containsKey("params")){
            JSONObject params = body.getJSONObject("params");
            assignee = params.getStr("assignee");
        }

        TaskQuery query = taskService.createTaskQuery();
        if(!StrUtil.isEmpty(assignee)){
            query.taskAssignee(assignee);
        }
        List<Task> taskList = query.orderByTaskCreateTime().desc().listPage((int)start,(int)size);
        List<TodoTaskDto> records = taskList.stream().map(TodoTaskDto::from).collect(Collectors.toList());
        return Result.SUCCESS(records,"查询成功").setPage(current,size,query.count());
    }

    /** 提交流程待办任务 */
    @PostMapping(value="/submit",consumes = {MediaType.APPLICATION_JSON_VALUE})
    @PreAuthorize("hasAnyAuthority('ADMIN','API_WORKFLOW_TODOTASK_SUBMIT')")
    public Object submit(@RequestBody JSONObject body){
        JSONObject result = new JSONObject();
        result.set("success",false)
                .set("message","提交任务失败");

        if(body.containsKey("params")) {
            JSONObject params = body.getJSONObject("params");
            String taskId = params.getStr("taskId");
            Map<String,Object> variables = params.getJSONObject("variables");
            taskService.complete(taskId, variables);
            result.set("success",true).set("message","提交任务成功");
        }
        return result;
    }





}
